/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.bumblebee.sessions;

import com.bumblebee.entities.Room;
import java.sql.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author numessi
 */
@Stateless
public class RoomFacade implements RoomFacadeLocal {
    @PersistenceContext(unitName = "resort-management-ejbPU")
    private EntityManager em;

    public void create(Room room) {
        em.persist(room);
    }

    public void edit(Room room) {
        em.merge(room);
    }

    public void remove(Room room) {
        em.remove(em.merge(room));
    }

    public Room find(Object id) {
        return em.find(Room.class, id);
    }

    public List<Room> findAll() {
        return em.createQuery("select object(o) from Room as o").getResultList();
    }

    public List<Room> findRange(int[] range) {
        Query q = em.createQuery("select object(o) from Room as o");
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        return ((Long) em.createQuery("select count(o) from Room as o").getSingleResult()).intValue();
    }
    public List<Room> getAvailableRooms(String location_id, Date arrival_date, Date departure_date) {
        String query = "SELECT * FROM Room WHERE room_location=" +location_id+ " AND room_id NOT IN " +
                "(SELECT room_id FROM Booking WHERE " +
                "'"+arrival_date+"'  BETWEEN Booking.arrival_date AND Booking.departure_date OR " +
                "'"+departure_date+"' BETWEEN Booking.arrival_date AND Booking.departure_date)";
        Query q = em.createNativeQuery(query, Room.class);
        List<Room> result = q.getResultList();
        return result;
    }

     public List<Room> getAvailableRooms(Date arrival_date, Date departure_date) {
        String query = "SELECT * FROM Room WHERE room_id NOT IN " +
                "(SELECT room_id FROM Booking WHERE " +
                "'"+arrival_date+"' BETWEEN Booking.arrival_date AND Booking.departure_date OR" +
                "'"+departure_date+"' BETWEEN Booking.arrival_date AND Booking.departure_date)";
        Query q = em.createNativeQuery(query, Room.class);
        List<Room> result = q.getResultList();
        return result;
    }

}
